#include "config.h"
#include <string>
#include <string.h>
#include <unistd.h>

#include "tools.h"

config *config::get()
{
    static config _s;
    return &_s;
}

config::config()
{
    m_Lua = luaL_newstate();
    luaL_openlibs(m_Lua);
}

config::~config()
{
    lua_close(m_Lua);
}

bool config::init(const char *app)
{
    char path[PATH_MAX] = {0};
    memset(path, 0, PATH_MAX);
    sprintf(path, "../app/%s/settings.lua", app);

    //脚本引用路径设置
    char lib_path[PATH_MAX] = {0};
    memset(lib_path, 0, PATH_MAX);
    sprintf(lib_path, "package.path = '%s../app/%s/?.lua;'..package.path", path::get_current_dir().c_str(), app);
    m_package_path = lib_path;
    luaL_dostring(m_Lua, lib_path);

    //加载settings.lua
    int ret = luaL_dofile(m_Lua, path);
    if (0 != ret)
    {
        printf("加载配置文件失败，失败原因：%s\n", lua_tostring(m_Lua, -1));
        return false;
    }

    //加载urls.lua
    sprintf(path, "../app/%s/urls.lua", app);
    m_urls_path = path;
    ret = luaL_dofile(m_Lua, path);
    if (0 != ret)
    {
        printf("加载路由文件失败，失败原因：%s\n", lua_tostring(m_Lua, -1));
        return false;
    }

    m_app_name = app;

    //读取mysql相关配置
    read_mysql_config();

    return true;
}

std::string config::app_name()
{
    return m_app_name;
}

const char *config::urls_path()
{
    return m_urls_path.c_str();
}

const char *config::package_path()
{
    return m_package_path.c_str();
}

void config::read_mysql_config()
{
    lua_getglobal(m_Lua, "mysql");
    {
        lua_getfield(m_Lua, -1, "host");
        m_mysql_config.host = luaL_optstring(m_Lua, -1, "127.0.0.1");
        lua_pop(m_Lua, 1);
    }
    {
        lua_getfield(m_Lua, -1, "port");
        m_mysql_config.port = (int)luaL_optinteger(m_Lua, -1, 3306);
        lua_pop(m_Lua, 1);
    }
    {
        lua_getfield(m_Lua, -1, "username");
        m_mysql_config.username = luaL_optstring(m_Lua, -1, NULL);
        lua_pop(m_Lua, 1);
    }
    {
        lua_getfield(m_Lua, -1, "password");
        m_mysql_config.password = luaL_optstring(m_Lua, -1, NULL);
        lua_pop(m_Lua, 1);
    }
    {
        lua_getfield(m_Lua, -1, "sourcename");
        m_mysql_config.sourcename = luaL_optstring(m_Lua, -1, NULL);
        lua_pop(m_Lua, 1);
    }
    {
        lua_getfield(m_Lua, -1, "pool_size");
        m_mysql_config.max = (int)luaL_optinteger(m_Lua, -1, 1024);
        lua_pop(m_Lua, 1);
    }
    lua_pop(m_Lua, 1);
}

st_mysql_config &config::get_mysql_config()
{
    return m_mysql_config;
}